﻿using System;
using System.Collections.Generic;
using System.Text;


namespace Magenic.CodeMastery.SharePoint.PMO
{
    /// <summary>
    /// This should be an implementation of an interface...but it's not (yet).
    /// </summary>
    public class ProjectRepository
    {
        public Project[] GetProjectsOrderedForDisplay()
        {
            int howMany = gen.Next(10, 20);
            List<Project> items = new List<Project>();
            for (int index = 0; index < howMany; ++index)
                items.Add(CreateRandomProject());
            Project[] ordered = OrderProjectsForDisplay(items.ToArray());
            return ordered;
        }

        public Project CreateRandomProject()
        {
            String[] names = { "Alice", "Bob", "Carol", "Dave" };

            Project item = new Project();
            //item.Name = "Project " + DateTime.Now.ToString("");
            item.Start = randomizedStart();
            item.Name = "P" + item.Start.ToString("ddmm");
            item.Finish = randomizedFinish(new DateTime(2010, 12, 31), item.Start);
            item.Manager = names[gen.Next(0, 4)];
            return item;
        }

        private DateTime randomizedStart()
        {
            int delta = gen.Next(-60, 90);
            return DateTime.Now.AddDays(delta);
        }

        private DateTime randomizedFinish(DateTime lastDayDisplayed, DateTime start)
        {
            //int remaining = lastDayDisplayed.Subtract(start).Days;
            //int delta = gen.Next(1, remaining);
            //return DateTime.Now.AddDays(delta);

            return start.AddDays(gen.Next(0, 45));
        }


        /// <summary>
        /// The project list needs to be sorted by PM name and Finish date to
        /// support collapsing rows.  If this can be done in the query just
        /// comment out the appropriate portions below.  Otherwise, this will
        /// brute force sort the projects in memory (needed this for testing
        /// anyway).
        /// </summary>
        /// <param name="projects"></param>
        /// <returns></returns>
        public Project[] OrderProjectsForDisplay(Project[] projects)
        {
            List<Project> sorted = new List<Project>(projects);
            sorted.Sort(delegate(Project lhs, Project rhs)
            {
                int result = lhs.Manager.CompareTo(rhs.Manager);
                if (result != 0)
                    return result;
                return lhs.Finish.Subtract(rhs.Finish).Days;
            });
            return sorted.ToArray();
        }

        private static Random gen = new Random((int)DateTime.Now.Ticks);
    }
}